import React, {CSSProperties, ReactNode, RefObject} from "react";
import Form, {FormVJsonProp, PageState} from './form'
import {render as renderJson, VJsonComponent, VJsonComponentBase,} from "../../factory";
import _ from 'lodash'
import {Button as AntdButton} from "antd"
import * as mobx from "mobx";
import {toJS} from "mobx";
import {DownOutlined, UpOutlined} from '@ant-design/icons'
import {colSetting, rowsColsInner} from "../../filter/rowcols";
import {Scope} from "../../scope";
import {observer} from 'mobx-react'
import {IObservableValue} from "mobx/lib/internal";
import {YvanEventDispatch} from "../..";

export interface FormPlusVJsonProp extends FormVJsonProp {
    title: string | ReactNode
    defaultExpand?: boolean,
    hideExtendCol: false,
    hideExpand: false,
    hideReset: false,
    hideQuery: false
    extendColSpan?: number
    extendColStyle: CSSProperties,
    onExpandChange: (sender: FormPlus, form: Form) => any
    onResetClick: (sender: FormPlus, form: Form) => any
    onSubmitClick: (sender: FormPlus, form: Form) => any
}

export interface PagePlusState extends PageState {
    expand: boolean
}

// @ts-ignore
const ToggleExpand = observer(({expand}) => {
    return expand.get() ?
        <AntdButton type="link"
                    onClick={() => expand.set(false)}
                    style={{padding: '4px 0'}}
        >收起 <UpOutlined/></AntdButton>
        : <AntdButton type="link"
                      onClick={() => expand.set(true)}
                      style={{padding: '4px 0'}}
        >展开 <DownOutlined/></AntdButton>
});

@VJsonComponent({
    view: 'form-plus'
})
export default class FormPlus extends VJsonComponentBase<FormPlusVJsonProp, PagePlusState> {
    static defaultProps = {
        ...Form.defaultProps,
        extendColSpan: undefined,
        extendColStyle: {
            paddingTop: 0,
            marginBottom: '24px',
            textAlign: 'right'
        },
        defaultExpand: false,
        hideExtendCol: false,
        hideExpand: false,
        hideReset: false,
        hideQuery: false
    }

    itemsVJson: any
    expand!: IObservableValue<boolean>
    formRef: RefObject<Form> = React.createRef();

    constructor(props: any) {
        super(props);

        _.defaults(
            this.props.vjson,
            FormPlus.defaultProps
        )

        this.expand = mobx.observable.box(this.props.vjson.defaultExpand)
        this.expand.observe(()=>{
            YvanEventDispatch(this.props.vjson.onExpandChange, this, this.formRef.current)
        })

        const items = toJS(this.props.vjson.items)
        const itemsAfter = toJS(this.props.vjson.itemsAfter)
        const scope: Scope<any, any> = this.props.$context.scopeInstance

        // 将 items 转换为 rows/cols 结构
        const [row1] = rowsColsInner([
            {cols: items}
        ])

        // 将 items 转换为 rows/cols 结构
        const [row2] = rowsColsInner([
            {cols: itemsAfter}
        ])

        let extendCount = 0
        _.forEach(row1.items, (item) => {
            if (item.isExtend === true || item.items[0].isExtend === true) {
                item.visible = {
                    $watch: () => {
                        // console.log('watch visible changed', this.expand.get())
                        return this.expand.get()
                    }
                }
                extendCount++
            }
        })

        _.forEach(row2.items, (item) => {
            if (item.isExtend === true || item.items[0].isExtend === true) {
                item.visible = {
                    $watch: () => {
                        // console.log('watch visible changed', this.expand.get())
                        return this.expand.get()
                    }
                }
                extendCount++
            }
        })

        if (!props.vjson.hideExtendCol) {
            row1.items.push({
                view: 'col',
                ...(props.vjson.extendColSpan ? {span: props.vjson.extendColSpan} : _.get(colSetting, 'weight1')),
                style: props.vjson.extendColStyle,
                items: [
                    {
                        view: 'space',
                        items: [
                            {
                                view: 'button',
                                text: '查询',
                                type: 'primary',
                                // icon: 'fa fa-search',
                                visible: !this.props.vjson.hideQuery,
                                onClick: this.submitClick.bind(this)
                            },
                            {
                                view: 'button',
                                text: '重置',
                                // icon: 'fa fa-times',
                                visible: !this.props.vjson.hideReset,
                                onClick: this.resetClick.bind(this)
                            },
                            // <AntdButton key={_.uniqueId("_")}
                            //             onClick={this.resetClick.bind(this)}>重置</AntdButton>,
                            //
                            // <AntdButton key={_.uniqueId("_")} type="primary"
                            //             onClick={this.submitClick.bind(this)}>查询</AntdButton>,
                            (() => (!this.props.vjson.hideExpand && extendCount > 0)
                                    ? <ToggleExpand key={_.uniqueId("_")} expand={this.expand}/>
                                    : null
                            )()
                        ]
                    }
                ]
            })
        }


        if (itemsAfter?.length > 0) {
            _.forEach(row2.items, (item) => {
                row1.items.push(item)
            })
        }

        this.itemsVJson = scope.$$({
            ..._.omit(props.vjson, ['items', 'view']),
            view: 'form',
            ref: '',
            className: 'yvan-form-plus',
            items: [
                {
                    view: 'row',
                    items: row1.items
                }
            ]
        })
    }

    getForm(): null | Form {
        return this.formRef.current
    }

    resetClick() {
        return YvanEventDispatch(this.props.vjson.onResetClick, this, this.formRef.current)
    }

    submitClick() {
        return YvanEventDispatch(this.props.vjson.onSubmitClick, this, this.formRef.current)
    }

    // @ts-ignore
    render() {
        if (!this.props.vjson.visible) {
            return null
        }

        return renderJson(this, this.itemsVJson, undefined, this.formRef)
    }
}
